class DocumentsController < ApplicationController
  require 'rubygems'

  def uploadFile

      Document.save(params[:upload])
      redirect_to :action => :done

  end

  def download

    send_file "#{RAILS_ROOT}/Documents/#{params[:file]}", :type => "application/msword", :disposition => "attachment"

  end

  def fetch

    token = Token.find(params[:token])
    if !token.nil?
      if token.created_at > 1.hour.ago
        send_file "#{RAILS_ROOT}/Documents/#{token.data}", :type => "application/msword", :disposition => "attachment"
      else
        render :inline => "Session expired. Go back and try again."
      end
        token.destroy
    else
      render :inline => "You don't have permission to view this."
    end

  end

  def view

    file_token = Token.new
    file_token.category = "Document"
    file_token.data = params[:file]
    file_token.save
    @token_id = file_token.id

  end

  def list

    Dir.chdir("#{RAILS_ROOT}/Documents/") do
      @documents = Dir.glob("*")
    end

    if (params[:filters] != nil and params[:filters][:type] != "")

      @filter = params[:filters][:type]
      @filter = @filter == "Pledge Meeting Minutes" ? "0" :
                @filter == "Active Meeting Minutes" ? "1" :
                @filter == "Exec Meeting Minutes" ? "2" :
                @filter == "Budget" ? "3" :
                @filter == "Governing Documents" ? "4" :
                @filter == "SRC" ? "5" :
                @filter == "Officer Reports" ? "6" : "7"

      @filtered = []

      while @documents.length > 0 do

        @temp = @documents.pop
        if (@temp[0..0] == @filter)
          @filtered.push(@temp)
        end

      end
      @documents = @filtered

    end

    @documents.sort! { |a,b| Time.parse(a[1, 10]) <=> Time.parse(b[1, 10]) }
    @documents = @documents.reverse

  end

  def remove

    Document.delete(params[:document])
    redirect_to :action => "list"

  end

end
